package com.hhu.wangzb.server.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.hhu.wangzb.common.entity.UserEntity;
import com.hhu.wangzb.common.exception.CustomException;
import com.hhu.wangzb.common.utils.QueryMap;
import com.hhu.wangzb.server.service.AuthenticateService;
import com.hhu.wangzb.server.service.UserService;
import com.hhu.wangzb.shiro.util.MD5Utils;
import org.apache.http.HttpStatus;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class AuthenticateServiceImpl implements AuthenticateService {

    @Autowired
    UserService userService;

    @Override
    public UserEntity authenticate(String username, String password) {

        QueryMap queryMap = new QueryMap();

        // 根据用户名、状态查询
        queryMap.put("username", username);

        UserEntity user = userService.queryByParamsMap(queryMap);

        // 对应用户名信息不存在
        if (user == null) throw new CustomException("用户名或密码不正确");
        // 账户状态异常
        if (user.getStatus() != 1) throw new CustomException("账户状态异常");
        // 密码不匹配
        if (!MD5Utils.validPasswd(password, user.getPassword())) throw new CustomException("用户名或密码不正确");

        // 保存认证信息 登陆校验的功能已经在上面完成了，这里只需要保存认证信息
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        subject.login(token);

        return user;
    }
}
